from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone

User = get_user_model()


class Course(models.Model):
    """课程"""
    DIFFICULTY_CHOICES = [
        ('beginner', '初级'),
        ('intermediate', '中级'),
        ('advanced', '高级'),
        ('expert', '专家级')
    ]
    
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已发布'),
        ('archived', '已归档')
    ]
    
    title = models.CharField(max_length=200, verbose_name="课程标题")
    description = models.TextField(verbose_name="课程描述")
    cover_image = models.CharField(max_length=500, blank=True, null=True, verbose_name="封面图")
    
    # 关联
    instructor = models.ForeignKey(User, on_delete=models.CASCADE, related_name='taught_courses', verbose_name="讲师")
    
    # 课程属性
    difficulty = models.CharField(max_length=20, choices=DIFFICULTY_CHOICES, verbose_name="难度")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name="状态")
    tags = models.JSONField(default=list, verbose_name="标签")
    prerequisites = models.JSONField(default=list, verbose_name="先决条件")
    
    # 统计
    estimated_duration = models.PositiveIntegerField(help_text="预计学习时长(分钟)", verbose_name="预计时长")
    enrolled_count = models.PositiveIntegerField(default=0, verbose_name="报名人数")
    completion_rate = models.FloatField(default=0.0, verbose_name="完成率")
    
    # 评价
    rating = models.FloatField(default=0.0, verbose_name="评分")
    rating_count = models.PositiveIntegerField(default=0, verbose_name="评分次数")
    
    # 时间戳
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    published_at = models.DateTimeField(blank=True, null=True, verbose_name="发布时间")

    class Meta:
        verbose_name = "课程"
        verbose_name_plural = "课程"
        db_table = 'learning_course'
        ordering = ['-created_at']

    def __str__(self):
        return self.title


class Lesson(models.Model):
    """课时"""
    LESSON_TYPE_CHOICES = [
        ('video', '视频'),
        ('text', '文本'),
        ('quiz', '测验'),
        ('exercise', '练习'),
        ('discussion', '讨论')
    ]
    
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='lessons')
    title = models.CharField(max_length=200, verbose_name="课时标题")
    description = models.TextField(blank=True, verbose_name="课时描述")
    
    # 课时内容
    lesson_type = models.CharField(max_length=20, choices=LESSON_TYPE_CHOICES, verbose_name="课时类型")
    content = models.TextField(verbose_name="课时内容")
    video_url = models.URLField(blank=True, null=True, verbose_name="视频链接")
    duration = models.PositiveIntegerField(default=0, verbose_name="时长(分钟)")
    
    # 排序和状态
    order = models.PositiveIntegerField(default=0, verbose_name="排序")
    is_free = models.BooleanField(default=False, verbose_name="免费")
    is_published = models.BooleanField(default=False, verbose_name="已发布")
    
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "课时"
        verbose_name_plural = "课时"
        db_table = 'learning_lesson'
        ordering = ['course', 'order']

    def __str__(self):
        return f"{self.course.title} - {self.title}"


class Enrollment(models.Model):
    """课程报名"""
    STATUS_CHOICES = [
        ('active', '进行中'),
        ('completed', '已完成'),
        ('paused', '暂停'),
        ('dropped', '已退出')
    ]
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='enrollments')
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='enrollments')
    
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name="状态")
    progress = models.FloatField(default=0.0, verbose_name="进度百分比")
    
    # 时间追踪
    enrolled_at = models.DateTimeField(default=timezone.now, verbose_name="报名时间")
    started_at = models.DateTimeField(blank=True, null=True, verbose_name="开始学习时间")
    completed_at = models.DateTimeField(blank=True, null=True, verbose_name="完成时间")
    last_accessed_at = models.DateTimeField(blank=True, null=True, verbose_name="最后访问时间")

    class Meta:
        verbose_name = "课程报名"
        verbose_name_plural = "课程报名"
        db_table = 'learning_enrollment'
        unique_together = ['user', 'course']

    def __str__(self):
        return f"{self.user.username} - {self.course.title}"


class LessonProgress(models.Model):
    """课时进度"""
    enrollment = models.ForeignKey(Enrollment, on_delete=models.CASCADE, related_name='lesson_progress')
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE)
    
    is_completed = models.BooleanField(default=False, verbose_name="是否完成")
    progress = models.FloatField(default=0.0, verbose_name="进度百分比")
    time_spent = models.PositiveIntegerField(default=0, verbose_name="学习时长(秒)")
    
    started_at = models.DateTimeField(blank=True, null=True, verbose_name="开始时间")
    completed_at = models.DateTimeField(blank=True, null=True, verbose_name="完成时间")
    last_accessed_at = models.DateTimeField(auto_now=True, verbose_name="最后访问时间")

    class Meta:
        verbose_name = "课时进度"
        verbose_name_plural = "课时进度"
        db_table = 'learning_lesson_progress'
        unique_together = ['enrollment', 'lesson']

    def __str__(self):
        return f"{self.enrollment.user.username} - {self.lesson.title}"


class StudySession(models.Model):
    """学习会话"""
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='study_sessions')
    course = models.ForeignKey(Course, on_delete=models.CASCADE, blank=True, null=True)
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, blank=True, null=True)
    
    # 会话数据
    duration = models.PositiveIntegerField(verbose_name="时长(秒)")
    activities = models.JSONField(default=list, verbose_name="活动记录")
    
    started_at = models.DateTimeField(verbose_name="开始时间")
    ended_at = models.DateTimeField(verbose_name="结束时间")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")

    class Meta:
        verbose_name = "学习会话"
        verbose_name_plural = "学习会话"
        db_table = 'learning_study_session'
        ordering = ['-started_at']

    def __str__(self):
        return f"{self.user.username} - {self.started_at.date()}"


class Quiz(models.Model):
    """测验"""
    lesson = models.ForeignKey(Lesson, on_delete=models.CASCADE, related_name='quizzes')
    title = models.CharField(max_length=200, verbose_name="测验标题")
    description = models.TextField(blank=True, verbose_name="测验描述")
    
    time_limit = models.PositiveIntegerField(blank=True, null=True, verbose_name="时间限制(分钟)")
    passing_score = models.PositiveIntegerField(default=60, verbose_name="及格分数")
    max_attempts = models.PositiveIntegerField(default=3, verbose_name="最大尝试次数")
    
    is_active = models.BooleanField(default=True, verbose_name="是否激活")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")

    class Meta:
        verbose_name = "测验"
        verbose_name_plural = "测验"
        db_table = 'learning_quiz'

    def __str__(self):
        return self.title


class Question(models.Model):
    """测验题目"""
    QUESTION_TYPE_CHOICES = [
        ('single', '单选题'),
        ('multiple', '多选题'),
        ('text', '填空题'),
        ('essay', '问答题')
    ]
    
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
    question_type = models.CharField(max_length=20, choices=QUESTION_TYPE_CHOICES, verbose_name="题目类型")
    question_text = models.TextField(verbose_name="题目内容")
    options = models.JSONField(default=list, verbose_name="选项")
    correct_answer = models.JSONField(verbose_name="正确答案")
    explanation = models.TextField(blank=True, verbose_name="解释")
    points = models.PositiveIntegerField(default=1, verbose_name="分值")
    order = models.PositiveIntegerField(default=0, verbose_name="排序")

    class Meta:
        verbose_name = "测验题目"
        verbose_name_plural = "测验题目"
        db_table = 'learning_question'
        ordering = ['quiz', 'order']

    def __str__(self):
        return f"{self.quiz.title} - {self.question_text[:50]}"